package modellstadt.geom;


import processing.core.PVector;


public class Plane {
	public PVector origin;
	public PVector normal;
	public Plane(PVector o, PVector n){
		origin=o;
		normal=n;
	}

	public Plane(PVector p1, PVector p2, PVector p3) {
		origin = p1;
		PVector v = PVector.sub(p3, p2);
		PVector u = PVector.sub(p2, p1);
		normal = new PVector();
		PVector.cross(v, u, normal);
		normal.normalize();
	}
	public Plane(float x1,float y1,float z1,float x2,float y2,float z2,float x3,float y3,float z3) {
		this(new PVector(x1,y1,z1),new PVector(x2,y2,z2),new PVector(x3,y3,z3));
	}
	public PVector segmentPlaneIntersection(PVector s1, PVector s2) {
		PVector u = PVector.sub(s2, s1);
		PVector w = PVector.sub(s1, origin);
		float d = PVector.dot(normal, u);
		float n = -PVector.dot(normal, w);
		if (Math.abs(d) < 0.0000001) // segment is parallel to plane
			return null;
		float t = n / d;
		if (t < 0 || t > 1)
			return null; // no intersection with Segment
		return new PVector(s1.x + t * u.x, s1.y + t * u.y, s1.z + t * u.z);
	}
	public PVector linePlaneIntersection(float x,float y,float z,float dx,float dy,float dz) {
		return linePlaneIntersection(new PVector(x,y,z),new PVector(dx,dy,dz));
	}
	public PVector linePlaneIntersection(PVector s1, PVector u) {
		PVector w = PVector.sub(s1, origin);
		float d = PVector.dot(normal, u);
		float n = -PVector.dot(normal, w);
		if (Math.abs(d) < 0.0000001) // segment is parallel to plane
			return null;
		float t = n / d;
		
		return new PVector(s1.x + t * u.x, s1.y + t * u.y, s1.z + t * u.z);
	}

	
	public float getDistance(float x,float y,float z){
		float d0=-normal.dot(origin);
		return d0+normal.dot(x,y,z);
	}
	public float getDistance(PVector v){
		return getDistance(v.x,v.y,v.z);
	}
}
